﻿using System.Collections.Generic;
using System.Data.Common;
using Jayden.Dll.Core;
using Jayden.Dll.Core.Persistence;
using Jayden.Dll.Core.Persistence.Data;
using Jayden.Dll.Core.Persistence.Data.SQLite;
using Jayden.Dll.Core.Persistence.Models;

namespace Jayden.Dll.Entities.Common
{
	public class SQLitePostDataAccess : SQLiteDataAccess<Post>, PostDataAccess
	{
		public SQLitePostDataAccess(Configuration config, UnitOfWork uow, Entity entity) : base(config, uow, entity) { }

		public List<Post> ReadByCategory(string category, int page, int pageSize, out int totalRecords)
		{
			string clauseString = "Category IS NULL";
			if (category != null)
				clauseString = "Category=@Category";

			string countCommandText = Helper.GenerateCount(Entity.Table.TableName, clauseString, null);
			using (DbCommandProxy countCommand = CreateCommand(countCommandText))
			{
				if(category != null)
					CreateParameter(countCommand, "Category", category);
				object countObject = countCommand.Command.ExecuteScalar();
				string countString = countObject == null ? "0" : countObject.ToString();
				totalRecords = int.Parse(countString);
			}
			string selectCommandText = Helper.GenerateSelect(null, Entity.Table.TableName, clauseString, null, new string[] { "DateTime DESC", "CreationDate DESC" }, pageSize, page * pageSize);
			using (DbCommandProxy selectCommand = CreateCommand(selectCommandText))
			{
				if (category != null)
					CreateParameter(selectCommand, "Category", category);
				using (DbDataReader reader = selectCommand.Command.ExecuteReader())
				{
					List<Post> posts = new List<Post>(EnumerateFromReader(reader));
					return posts;
				}
			}
		}
	}
}
